import { createSlice, PayloadAction } from '@reduxjs/toolkit';
export type TodoType = {
  id: string;
  name: string;
  done: boolean;
};
export const initialState: TodoType[] = [
  {
    id: '001',
    name: '吃饭',
    done: true,
  },
  {
    id: '002',
    name: '睡觉',
    done: true,
  },
  {
    id: '003',
    name: '打代码',
    done: false,
  },
];
export const todoListSlice = createSlice({
  name: 'todoList',
  initialState,
  reducers: {
    addTodo(state: TodoType[], action: PayloadAction<TodoType>) {
      state.push(action.payload);
    },
    removeTodo(state: TodoType[], action: PayloadAction<string>) {
      const index = state.findIndex((item) => item.id === action.payload);
      state.splice(index, 1);
    },
    updateTodo(state: TodoType[], action: PayloadAction<TodoType>) {
      console.log('updateTodo');
      const index = state.findIndex((item) => item.id === action.payload.id);
      state[index] = action.payload;
    },
    checkAll(state: TodoType[], action: PayloadAction<boolean>) {
      state.forEach((item) => {
        item.done = action.payload;
      });
    },
    clearDone(state: TodoType[]) {
      const newList = state.filter((item) => !item.done);
      console.log('newList', newList);
      state.splice(0, state.length);
      state.push(...newList);
      console.log('state', state);
    },
  },
});

export const { addTodo, removeTodo, updateTodo, checkAll, clearDone } = todoListSlice.actions;
export default todoListSlice.reducer;
